package cn.benma666.sjsj.job;

import cn.benma666.domain.SysSjglZnjh;
import cn.benma666.iframe.Conf;
import cn.benma666.iframe.InterfaceLog;
import cn.benma666.myutils.DateUtil;
import cn.benma666.sjsj.myutils.ThreadPool;
import cn.benma666.sjsj.znjh.MyZnjh;
import cn.benma666.sjzt.BasicSjzt;
import cn.benma666.sjzt.Db;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 智能交换
 */
@Component
@XxlJob(value = "ZnjhHandler",init = "init")
public class ZnjhJob extends BasicJob{
    /**
     * 任务体
     */
    public void execute() throws Exception {
        start(this,getVal("jcjg"));
    }

    /**
     * 启动智能交换，支持多种方式启动
     * @param log 日志实现
     * @param jcjgStr 检测间隔表达式，将带s、m、h单位的字符串转为毫秒，nHnMnS（n为个数），eg：2M
     */
    public static void start(InterfaceLog log,String jcjgStr){
        //加载交换
        List<SysSjglZnjh> znjhList = Db.use().lambdaQuery(SysSjglZnjh.class)
                .andEq(SysSjglZnjh::getJhjd, Conf.getAppdm())
                .andEq(SysSjglZnjh::getJtqzt,"1").select();
        for (SysSjglZnjh znjh:znjhList){
            log.info("开始启动交换任务：{}",znjh.getJhmc());
            BasicSjzt srzt = BasicSjzt.useSjzt(znjh.getSrzt());
            znjh.setTp(ThreadPool.use(znjh.getJhmc(),znjh.getTpc()));
            srzt.setZnjh(MyZnjh.use());
            srzt.startListener(znjh,log);
        }
        try {
            long jcjg = DateUtil.scSjStrToLong(jcjgStr);
            while (true){
                Thread.sleep(jcjg);
                BasicSjzt.jcListener(log);
                log.info("持续运行运行中：{}",BasicSjzt.jtqMap.size());
            }
        }catch (InterruptedException e){
            BasicSjzt.stopListener();
            XxlJobHelper.handleSuccess("结束运行，停止相关任务");
        }
    }
}
